package gov.gfbzb.advice.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import gov.gfbzb.advice.controller.dto.AdviceDTO;
import gov.gfbzb.advice.controller.vo.AdviceVO;
import gov.gfbzb.advice.entity.Advice;
import gov.gfbzb.advice.exception.BusinessException;
import gov.gfbzb.advice.exception.ErrorCode;
import gov.gfbzb.advice.mapper.AdviceMapper;
import gov.gfbzb.advice.service.IAdviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import gov.gfbzb.advice.service.IChatService;
import gov.gfbzb.advice.util.Result;
import gov.gfbzb.advice.util.StringUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * AdviceServiceImpl 服务实现类
 * @author 小宇
 * @since 2025-07-05
 */
@Log4j2
@Service
public class AdviceServiceImpl extends ServiceImpl<AdviceMapper, Advice> implements IAdviceService {

    @Autowired
    private IChatService chatService;

    @Override
    public Map<String, Object> pageCondition(Integer pageNum, Integer pageSize, Boolean viewCount,String county,String keyWord,String cardOrPhone, Boolean isPass) {
        QueryWrapper<Advice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        // 手机号、身份证精确查询
        if (StringUtils.isNotBlank(keyWord)){
            queryWrapper.and(query -> {
                query.like("title", keyWord)
                        .or()
                        .like("content", keyWord);
            });
        }
        if (StringUtils.isNotBlank(cardOrPhone)){
            queryWrapper.and(query -> {
                query.eq("phone", cardOrPhone)
                        .or()
                        .eq("id_card", cardOrPhone);
            });
        }

        if (viewCount!=null&&viewCount){
            // 按浏览次数降序
            queryWrapper.orderByDesc("view_count");
        }else {
            // 按id降序
            queryWrapper.orderByDesc("id");
        }
        // 模糊查询区县
        if (StringUtils.isNotBlank(county)){
            queryWrapper.like("county", county);
        }
        // 是否审核通过
        if (isPass){
            queryWrapper.eq("question_status",1);
        }else {
            // 待审核和已驳回
            queryWrapper.and(query -> {
                query.eq("question_status",0)
                        .or()
                        .eq("question_status",2);
            });
        }

        // 获取分页数据
        Page<Advice> page = this.page(new Page<>(pageNum, pageSize), queryWrapper);

        // 转化为 VO
        List<AdviceVO> adviceVOList = page.getRecords().stream().map(advice -> {
            AdviceVO adviceVO = new AdviceVO();
            BeanUtils.copyProperties(advice, adviceVO);
            return adviceVO;
        }).toList();

        // 构建分页响应对象
        Map<String, Object> resultData = new HashMap<>();
        resultData.put("records", adviceVOList);        // 数据列表
        resultData.put("total", page.getTotal());       // 总记录数
        resultData.put("pages", page.getPages());       // 总页数
        resultData.put("current", page.getCurrent());   // 当前页码
        resultData.put("size", page.getSize());         // 每页大小
        return resultData;
    }

    @Override
    @Async("taskExecutor")
    public CompletableFuture<Void> saveAndGetAdvice(AdviceDTO adviceDTO) {
        try {
            Advice advice = new Advice();
            BeanUtils.copyProperties(adviceDTO, advice);
            // 设置唯一问题码
            String questionNo = StringUtil.generateQuestionNo();
            advice.setQuestionNo(questionNo);
            // 设置未审核
            advice.setQuestionStatus(0);
            advice.setViewCount(0);
            // 保存
            this.save(advice);
            log.info("==保存成功==\n{}",advice);
            // 获取回复
            String question = advice.getTitle();
            if (!advice.getContent().isEmpty()){
                question+=":"+advice.getContent();
            }
            this.getAndSaveAdvice(questionNo,question);
        }catch (Exception e){
            log.error(e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误，请联系管理员");
        }
        return CompletableFuture.completedFuture(null);
    }

    @Override
    @Async("taskExecutor")
    public CompletableFuture<Void> getAndSaveAdvice(String questionNo, String question) {
        try {
            // 从DeepSeek获取建议
            CompletableFuture<String> advice = chatService.advice(question);
            String answer = advice.get();
            log.info("==DeepSeek建议生成成功==\n{}",answer);
            // 通过唯一问题码查询建议
            QueryWrapper<Advice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("question_no", questionNo);
            Advice theAdvice = this.getOne(queryWrapper);
            // 设置 建议
            theAdvice.setAnswer(answer);
            // 保存
            this.updateById(theAdvice);
            return CompletableFuture.completedFuture(null);
        } catch (Exception e) {
            // 记录异常日志
            log.error("获取并保存建议失败", e);
            // 可选择返回失败的CompletableFuture
            return CompletableFuture.failedFuture(e);
        }
    }
}
